package com.jackaltsc.mydemolist.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.jackaltsc.mydemolist.R;
import com.jackaltsc.mydemolist.entity.Student;

import java.util.List;

/**
 * 自定义的Adapter 比较经典的写法 这里主要是getView里的写法要与Recyclerview对比来看
 * Created by JackalTsc on 2016/7/13.
 */
public class StuListAdapter extends BaseAdapter {

    //数据集合
    private List<Student> mData;
    private LayoutInflater mInflater;

    public StuListAdapter(Context context, List<Student> data) {
        mData = data;
        mInflater = LayoutInflater.from(context);
    }

    //返回数据集合的数量
    @Override
    public int getCount() {
        return mData.size();
    }

    //返回指定位置的数据
    @Override
    public Student getItem(int position) {
        return mData.get(position);
    }

    //返回指定位置的数据项id
    @Override
    public long getItemId(int position) {
        return position;
    }

    //生成视图
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;

        //如果没有可以复用的View
        if (convertView == null) {
            //通过LayoutInflater实例化布局
            convertView = mInflater.inflate(R.layout.view_item_stulist, null);

            holder = new ViewHolder();
            holder.ivStuPhoto = (ImageView) convertView.findViewById(R.id.iv_photo);
            holder.tvStuName = (TextView) convertView.findViewById(R.id.tv_name);

            convertView.setTag(holder);

        } else {
            //如果有可以复用的View 就通过tag找到缓存的布局
            holder = (ViewHolder) convertView.getTag();
        }

        holder.ivStuPhoto.setImageResource(mData.get(position).getStuPhotoId());
        holder.tvStuName.setText(mData.get(position).getStuName());

        return convertView;

    }

    //静态类
    static class ViewHolder {
        ImageView ivStuPhoto;
        TextView tvStuName;
    }
}
